package com.mapbased.wfw;

import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2004</p>
 *
 * <p>Company: mapbased.com</p>
 *
 * @author chy(Baily),some code from htmlparse.org
 * @version 1.0
 */
public class Util
{

    /**
     * Load resource fro given class and locale
     * @param c Class
     * @param locale String
     * @return Properties
     * @throws IOException
     */
    final public static java.util.Properties loadRes(Class c,String locale)
        throws IOException
    {

        String cn=c.getName().replace('.','/');
        URL u=null;
        if(locale != null)
        {
            u=c.getClassLoader().getResource(cn + '_' + locale +
                                             ".properties");
            if(u == null)
            {
                int i=locale.indexOf('_');
                if(i > 0)
                {
                    u=c.getClassLoader().getResource(cn + '_' +
                        locale.substring(0,i) +
                        ".properties");

                }
            }

        }
        if(u == null)
        {
            u=c.getClassLoader().getResource(cn + ".properties");
        }
        Properties resStrings=null;
        if(u != null)
        {
            resStrings=new java.util.Properties();

            resStrings.load(u.openStream());

        }
        return resStrings;

    }

    public static void main(String[] d)
    {
        try
        {
            System.out.println(urlEncodeExcludeDelimiter(
                " http://ewww.eee.cc/ssffd/dfs大大/ sdsdss[][][][]sssssd.gif?asdaa=sdfs#dfsdf",
                "utf-8"));
        }
        catch(UnsupportedEncodingException ex)
        {
            ex.printStackTrace();
        }
    }

    public final static String removeSpace(String s)
    {
        if(s == null || s.equals(""))
        {
            return "";
        }
        if(s.trim().equals(""))
        {
            return " ";
        }

        String[] ss=s.split("\n");
        StringBuffer sb=new StringBuffer(s.length());
        for(int i=0;i < ss.length;i++)
        {
            String ts=ss[i].trim();
            if(!ts.equals(""))
            {
                sb.append(ts);
                if(i < ss.length - 1)
                {
                    sb.append("\n");
                }
//        else
//        {
//          sb.append(" ");
//        }
            }
        }

        return sb.toString();

    }

    public static void _main(String[] ss)
    {
        String s="     aaa              \n" +
            "bbbbbbbbbbbbbbbbbb          \n" +
            "|n   \\ // \" \'  \t      \n";

        System.out.println(s);

        System.out.println(toJsSafe(s));

        System.out.println(fromJsSafe(toJsSafe(s)));

    }

    /**
     * 把字符串转换到书写为javascript字符串安全的格式
     * @param s String
     * @return String
     */
    static final public String toJsSafe(String s)
    {
        if(s == null)
        {
            return "null";
        }
        StringBuffer sb=new StringBuffer((int)(s.length() * 1.04));
        for(int i=0;i < s.length();i++)
        {
            char c=s.charAt(i);
            /**
             *  if(si=="'")
                     {
                        ss+="\\'";
                     }
                     else if(si=="\n")
                     {
                        ss+="\\n";
                     }
                     else if(si=="\r")
                     {
                         ss+="\\r";
                     }
                     else if(si=='"')
                     {
                         ss+='\\"';
                     }
                     else if(si=="\t")
                     {
                         ss+="\\t";
                     }
                     else if(si=="\f")
                     {
                         ss+="\\f";
                     }
                     else if(si=="\b")
                     {
                         ss+="\\b";
                     }
                     else if(si=="/")
                     {
                         ss+="\\/";
                     }

                      else if(si=="\\")
                     {
                        ss+="\\\\";
                     }
                     else

             */
            switch(c)
            {
                case '\'':
                    sb.append("\\'");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '"':
                    sb.append("\\\"");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }
        return sb.toString();
    }

    static final public String fromJsSafe(String s)
    {
        if(s == null)
        {
            return "";
        }
        StringBuffer sb=new StringBuffer(s.length());
        boolean intrans=false;
        for(int i=0;i < s.length();i++)
        {
            char c=s.charAt(i);
            if(intrans)
            {
                switch(c)
                {
                    case 'n':
                        sb.append('\n');
                        break;
                    case 'r':
                        sb.append('\r');
                        break;
                    case 't':
                        sb.append('\t');
                        break;
                    case 'f':
                        sb.append('\f');
                        break;
                    case 'b':
                        sb.append('\b');
                        break;

                    default:
                        sb.append(c);
                        break;
                }
                intrans=false;
                continue;
            }
            if(c == '\\')
            {

                intrans=true;
            }
            else
            {
                sb.append(c);
            }

        }
        return sb.toString();

    }

    /**
     * remove <script> and other releate elements from the string
     * @param s String
     * @return String
     */
    final public static String removeScript(String s)
    {
        if(s == null)
        {
            return "";
        }
        int l=s.length();
        int lt=0;
        int gt=0;
        int b=0;
        StringBuffer doc=new StringBuffer(l);

        while(b >= 0)
        {

            lt=s.indexOf("<",b);
            if(lt < 0)
            {
                String t=s.substring(b);
                doc.append(t);
                return doc.toString();
            }
            String t=s.substring(b,lt);
            doc.append(t);

            gt=s.indexOf(">",lt);
            if(gt < 0)
            {

                doc.append(s.substring(lt));
                return doc.toString();
            }

            b=gt + 1;

            String ele=s.substring(lt + 1,gt);
            if(ele.startsWith("!--"))
            {
                if(ele.endsWith("--"))
                {

                }
                else
                {
                    b=s.indexOf("-->",gt) + 3;
                }
                continue;

            }

            doc.append("<");
            filterEle(ele,doc);
            doc.append(">");

        }
        return doc.toString();

    }

    static final String __BLOCKELES=" body html iframe frame ";
    static final String __BLOCKELEE=" /body /html /iframe /frame ";
    private static final void filterEle(String ele,StringBuffer doc)
    {
        // alert(ele)
        String[] p=ele.split(" ");
        String s=p[0].toLowerCase();

        if(__BLOCKELES.indexOf(' ' + s + ' ') >= 0)
        {
            if(ele.charAt(ele.length() - 1) == '/')
            {
                doc.append("div /");

            }
            else
            {
                doc.append("div ");

            }
            return;

        }
        if(__BLOCKELEE.indexOf(' ' + s + ' ') >= 0)
        {
            doc.append(" /div");
            return;

        }

        if(s.equals("script"))
        {
            if(ele.charAt(ele.length() - 1) == '/')
            {
                doc.append("!-- --");

            }
            else
            {
                doc.append("!-- ");

            }
            return;

        }
        if(s.equals("/script"))
        {
            doc.append(" --");
            return;

        }

        doc.append(s);

        for(int i=1;i < p.length;i++)
        {
            s=p[i].toLowerCase();
            if(s.startsWith("on"))
            {
                continue;
            }
            if(s.toLowerCase().indexOf("script") > 0)
            {
                continue;
            }
            doc.append(" " + p[i]);

        }

    }

    final public static String replaceToXmlPreTextarea(String s)
    {
        if(s == null)
        {
            return null;
        }
        StringBuffer sb=new StringBuffer(s.length() + 20);
        for(int i=0;i < s.length();i++)
        {
            char c=s.charAt(i);
            if(c == '<')
            {
                sb.append("&lt;");
            }
            else if(c == '>')
            {
                sb.append("&gt;");
            }
            else if(c == '&')
            {
                sb.append("&amp;");
            }
            else if(c == '"')
            {
                sb.append("&quot;");
            }
            else if(c == '\'')
            {
                sb.append("&#39;");
            }
            else
            {
                sb.append(c);
            }

        }
        return sb.toString();

    }

    final public static String replaceToXml(String s)
    {
        if(s == null)
        {
            return null;
        }
        StringBuffer sb=new StringBuffer(s.length() + 20);
        for(int i=0;i < s.length();i++)
        {
            char c=s.charAt(i);
            if(c == '<')
            {
                sb.append("&lt;");
            }
            else if(c == '>')
            {
                sb.append("&gt;");
            }
            else if(c == '&')
            {
                sb.append("&amp;");
            }
            else if(c == '"')
            {
                sb.append("&quot;");
            }
            else if(c == '\'')
            {
                sb.append("&#39;");
            }
            else if(c == ' ')
            {
                sb.append("&#32;");
            }
            else if(c == '\n')
            {
                sb.append("<br />");
            }
            else if(c == '\t')
            {
                sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            else
            {
                sb.append(c);
            }

        }
        return sb.toString();
    }

    private static final Class[] STRING_AGU=new Class[]
        {
        String.class};
    /**
     * Constract  an object of given class type ,parse the value from the string
     * a lot of tode to suppoert other object
     * current only support boolean and number
     *
     * @param c Class
     * @param s String
     * @return Object
     */
    public static final Object valueOf(Class c,String s)
    {
        if(c.isPrimitive())
        {

            try
            {
                Method m=c.getMethod("valueOf",STRING_AGU);
                return m.invoke((Object)null,new Object[]
                                {s});
            }

            catch(NoSuchMethodException ex)
            {
                return null;
            }
            catch(InvocationTargetException ex)
            {
                return null;
            }

            catch(IllegalArgumentException ex)
            {
                return null;
            }
            catch(IllegalAccessException ex)
            {
                return null;
            }

        }
        return null;

    }

    /**
     * javascrit format urlencode. (the unescape code is in chyspatial.jar com.chy.webgis.misc)
     * @param s String
     * @return String
     */
    public static String escape(String s)
    {
        StringBuffer sbuf=new StringBuffer();
        int len=s.length();
        for(int i=0;i < len;i++)
        {
            int ch=s.charAt(i);
            if(ch == ' ')
            { // space : map to '+'
                sbuf.append('+');
            }
            else if('A' <= ch && ch <= 'Z')
            { // 'A'..'Z' : as it was
                sbuf.append((char)ch);
            }
            else if('a' <= ch && ch <= 'z')
            { // 'a'..'z' : as it was
                sbuf.append((char)ch);
            }
            else if('0' <= ch && ch <= '9')
            { // '0'..'9' : as it was
                sbuf.append((char)ch);
            }
            else if(ch == '-' || ch == '_' // unreserved : as it was
                    || ch == '.' || ch == '!'
                    || ch == '~' || ch == '*'
                    || ch == '\'' || ch == '('
                    || ch == ')')
            {
                sbuf.append((char)ch);
            }
            else if(ch <= 0x007F)
            { // other ASCII : map to %XX
                sbuf.append('%');
                sbuf.append(hex[ch]);
            }
            else
            { // unicode : map to %uXXXX
                sbuf.append('%');
                sbuf.append('u');
                sbuf.append(hex[(ch >>> 8)]);
                sbuf.append(hex[(0x00FF & ch)]);
            }
        }
        return sbuf.toString();
    }

    private final static String[] hex=
        {
        "00","01","02","03","04","05","06","07","08","09","0A","0B","0C",
        "0D","0E","0F",
        "10","11","12","13","14","15","16","17","18","19","1A","1B","1C",
        "1D","1E","1F",
        "20","21","22","23","24","25","26","27","28","29","2A","2B","2C",
        "2D","2E","2F",
        "30","31","32","33","34","35","36","37","38","39","3A","3B","3C",
        "3D","3E","3F",
        "40","41","42","43","44","45","46","47","48","49","4A","4B","4C",
        "4D","4E","4F",
        "50","51","52","53","54","55","56","57","58","59","5A","5B","5C",
        "5D","5E","5F",
        "60","61","62","63","64","65","66","67","68","69","6A","6B","6C",
        "6D","6E","6F",
        "70","71","72","73","74","75","76","77","78","79","7A","7B","7C",
        "7D","7E","7F",
        "80","81","82","83","84","85","86","87","88","89","8A","8B","8C",
        "8D","8E","8F",
        "90","91","92","93","94","95","96","97","98","99","9A","9B","9C",
        "9D","9E","9F",
        "A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC",
        "AD","AE","AF",
        "B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC",
        "BD","BE","BF",
        "C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC",
        "CD","CE","CF",
        "D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC",
        "DD","DE","DF",
        "E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC",
        "ED","EE","EF",
        "F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC",
        "FD","FE","FF"
    };

    static BitSet dontNeedEncoding;
    static final int caseDiff=('a' - 'A');

    static
    {

        dontNeedEncoding=new BitSet(256);
        int i;
        for(i='a';i <= 'z';i++)
        {
            dontNeedEncoding.set(i);
        }
        for(i='A';i <= 'Z';i++)
        {
            dontNeedEncoding.set(i);
        }
        for(i='0';i <= '9';i++)
        {
            dontNeedEncoding.set(i);
        }
     //   dontNeedEncoding.set(' '); /* encoding a space to a + is done
     //   * in the encode() method */
       dontNeedEncoding.set('-');
        dontNeedEncoding.set('_');
        dontNeedEncoding.set('.');
        dontNeedEncoding.set('*');
        /////////////////////////////////////////////////
        dontNeedEncoding.set('!');
        dontNeedEncoding.set('~');
        dontNeedEncoding.set('\'');
        dontNeedEncoding.set('(');
        dontNeedEncoding.set(')');


        ///////////////////////////////////////
        dontNeedEncoding.set(';');
        dontNeedEncoding.set('/');
        dontNeedEncoding.set('?');
        dontNeedEncoding.set(':');
        dontNeedEncoding.set('&');
        dontNeedEncoding.set('=');
        //dontNeedEncoding.set('+');
        dontNeedEncoding.set('$');
        dontNeedEncoding.set(',');
        dontNeedEncoding.set('#');




    }

    public static String urlEncodeExcludeDelimiter(String s,String enc)
        throws UnsupportedEncodingException
    {

        boolean needToChange=false;
        boolean wroteUnencodedChar=false;
        int maxBytesPerChar=10; // rather arbitrary limit, but safe for now
        StringBuffer out=new StringBuffer(s.length());
        ByteArrayOutputStream buf=new ByteArrayOutputStream(maxBytesPerChar);

        OutputStreamWriter writer=new OutputStreamWriter(buf,enc);

        for(int i=0;i < s.length();i++)
        {
            int c=(int)s.charAt(i);
            //System.out.println("Examining character: " + c);
            if(dontNeedEncoding.get(c))
            {
                if(c == ' ')
                {
                    c='+';
                    needToChange=true;
                }
                //System.out.println("Storing: " + c);
                out.append((char)c);
                wroteUnencodedChar=true;
            }
            else
            {
                // convert to external encoding before hex conversion
                try
                {
                    if(wroteUnencodedChar)
                    { // Fix for 4407610
                        writer=new OutputStreamWriter(buf,enc);
                        wroteUnencodedChar=false;
                    }
                    writer.write(c);
                    /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                    if(c >= 0xD800 && c <= 0xDBFF)
                    {
                        /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                         */
                        if((i + 1) < s.length())
                        {
                            int d=(int)s.charAt(i + 1);
                            /*
                              System.out.println("\tExamining "
                              + Integer.toHexString(d));
                             */
                            if(d >= 0xDC00 && d <= 0xDFFF)
                            {
                                /*
                                  System.out.println("\t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                 */
                                writer.write(d);
                                i++;
                            }
                        }
                    }
                    writer.flush();
                }
                catch(IOException e)
                {
                    buf.reset();
                    continue;
                }
                byte[] ba=buf.toByteArray();
                for(int j=0;j < ba.length;j++)
                {
                    out.append('%');
                    char ch=Character.forDigit((ba[j] >> 4) & 0xF,16);
                    // converting to use uppercase letter as part of
                    // the hex value if ch is a letter.
                    if(Character.isLetter(ch))
                    {
                        ch-=caseDiff;
                    }
                    out.append(ch);
                    ch=Character.forDigit(ba[j] & 0xF,16);
                    if(Character.isLetter(ch))
                    {
                        ch-=caseDiff;
                    }
                    out.append(ch);
                }
                buf.reset();
                needToChange=true;
            }
        }

        return(needToChange ? out.toString() : s);
    }



}
